package com.jdbc.详解;

import org.junit.Test;

import java.sql.*;

//JDBC的快速入门
public class PreparedDemo {
/**
 * 用户登录
 */


    @Test
    public void testPreparedDemo() throws Exception {
        String url="jdbc:mysql:///db1";

        String username="root";
        String password="root";
        Connection conn=DriverManager.getConnection(url,username,password);


        //接收用户输入的  用户名和密码
//        String name="zhangsan";
//        String  pwd="123";
        String name="vfjgkugiugu";
        String  pwd="'or '1' = '1";

        //定义sql
        String sql="select * from tb_user where username=? and password=?";

        //获取pstmt对象
        PreparedStatement pstmt = conn.prepareStatement(sql);

        //设置？的值
        pstmt.setString(1,name);
        pstmt.setString(2,pwd);

        //执行sql
        ResultSet rs=pstmt.executeQuery();


        //判断是否成功
        if (rs.next()){
            System.out.println("登陆成功");
        }else {
            System.out.println("登陆失败");
        }


        //7.释放资源
        rs.close();
        pstmt.close();
        conn.close();


    }


    /**
     * sql注入
     * @throws Exception
     */

    @Test
    public void testUserLogin_Inject() throws Exception {
        String url="jdbc:mysql:///db1";

        String username="root";
        String password="root";
        Connection conn=DriverManager.getConnection(url,username,password);


        //接收用户输入的  用户名和密码
        String name="vfjgkugiugu";
        String  pwd="'or '1' = '1";

        //定义sql
        String sql="SELECT * FROM tb_user where username='"+name+"' and password='"+pwd+"'";

        //获取stmt对象
        Statement stmt = conn.createStatement();

        //执行sql
        ResultSet rs = stmt.executeQuery(sql);

        System.out.println(sql);//可以复制到navicat查看

        //判断是否成功
        if (rs.next()){
            System.out.println("登陆成功");
        }else {
            System.out.println("登陆失败");
        }


        //7.释放资源
        rs.close();
        stmt.close();
        conn.close();


    }
}
